package login

import (
	"beegoProject06/models/user"
	"beegoProject06/utils"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type LoginController struct {
	beego.Controller
}

func (c *LoginController) Get() {
	id, base64, err := utils.GetCaptcha()
	if err != nil {
		return
	}
	c.Data["captcha"] = utils.Captcha{Id: id, BS64: base64}
	c.TplName = "login/login.html"
}

func (c *LoginController) Post() {
	// 通过json方式，从前端获取四个值
	username := c.GetString("username")
	password := c.GetString("password")
	captcha := c.GetString("captcha")
	captcha_id := c.GetString("captcha_id")

	/* 打印查看数据接收效果 */
	fmt.Printf("用户名:%s 密码:%s 输入验证码:%s 验证码:%s\n", username, password, captcha, captcha_id)

	/* 查看验证码校验是否正确 */
	isOk := utils.VerityCaptcha(captcha_id, captcha)

	md5Pwd := utils.Md5Text(password)
	fmt.Println("MD5: 加密后密码", md5Pwd)

	// 初始化调用 models - user 结构体
	checkUser := user.User{}
	// 数据库查询
	o := orm.NewOrm()
	isExist := o.QueryTable("sys_user").Filter("user_name", username).Filter("password", md5Pwd).Exist()

	// 查询session
	o.QueryTable("sys_user").Filter("user_name", username).Filter("password", md5Pwd).One(&checkUser)

	// 用户名密码验证返回到前端
	resultMap := map[string]interface{}{}
	if !isExist {
		resultMap["code"] = 10001
		resultMap["msg"] = "用户名或密码错误"
		c.Data["json"] = resultMap
	} else if !isOk {
		resultMap["code"] = 10001
		resultMap["msg"] = "验证码错误错误"
		c.Data["json"] = resultMap
	} else if checkUser.IsActive == 0 {
		resultMap["code"] = 10001
		resultMap["msg"] = "该用户已停用，请联系管理员开通!"
		c.Data["json"] = resultMap
	} else {
		// 登录成功后设置session
		c.SetSession("id", checkUser.Id)
		resultMap["code"] = 200
		resultMap["msg"] = "登录成功"
		c.Data["json"] = resultMap
	}
	c.ServeJSON()

}

func (c *LoginController) ChangeCaptcha() {
	message := map[string]interface{}{}
	id, base64, err := utils.GetCaptcha()
	if err != nil {
		message["msg"] = "验证码错误"
		message["Code"] = 404
		c.Data["json"] = message
	} else {
		c.Data["json"] = utils.Captcha{Id: id, BS64: base64, Code: 200}
	}
	c.ServeJSON()
}
